<?php

namespace app\controllers\h5\uni;

use app\controllers\h5\base\H5Controller;
use app\models\system\SetSwiper;
use app\models\user\User;
use app\redis\Cache;

class CenterController extends H5Controller
{
    public function actionIndex()
    {
        $cache = Cache::get(Cache::$PAGE_CENTER);

        if (!$cache || true) {
            $data = [
                'swiper1' => $this->swiper(4),
                'swiper2' => $this->swiper(5),
            ];

            Cache::set(Cache::$PAGE_CENTER, json_encode($data));
        } else {
            $data = json_decode($cache, true);
        }

        return $this->successEncode($data);
    }

    private function swiper($category)
    {
        return SetSwiper::find()
            ->where(['status' => SetSwiper::$statusMapping['OK']])
            ->andWhere(['category_id' => $category])
            ->orderBy(['sort' => SORT_ASC, 'id' => SORT_DESC])
            ->with(['image'])
            ->asArray()
            ->all();
    }

    // 获取头像
    public function actionGetAvatar()
    {
        $model = User::findOne(['id' => $this->user->id]);

        if ($model['nickname']) {
            $model['nickname'] = base64_decode($model['nickname']);
        }

        return $this->successEncode([
            'avatar' => $model['avatar'],
            'nickname' => $model['nickname'],
            'id' => $model['id'],
        ]);
    }

    // 修改头像
    public function actionSetAvatar()
    {
        $nickname = $this->post('nickname');
        if ($nickname) {
            $nickname = base64_encode($nickname);
        } else {
            return $this->fail();
        }

        $model = User::findOne(['id' => $this->user->id]);
        $model->av = 1;
        $model->nickname = $nickname;
        $model->save();

        return $this->success();
    }

    // 删除
    public function actionDelAvatar()
    {
        $model = User::findOne(['id' => $this->user->id]);
        $model->av = 1;
        $model->avatar = '';
        $model->save();

        return $this->success();
    }
}